<template>
  <div>
    <!--  视频号名称  -->
    <TemplateText
      v-if="elementsKey.username"
      :ref="(el) => setItemRef(el, elementsKey.username.name)"
      :key="elementsKey.username.name"
      :loading="channelLoading"
      is-update
      is-channels
      :params="attributes[elementsKey.username.index]"
      @upload="handleFetchWechatChannelList"
      @change="handleWeChatChannelsChange"
    />
    <TemplateText
      v-else-if="channelsUserName"
      :ref="(el) => setItemRef(el, channelsUserName.name)"
      :key="channelsUserName.name"
      :loading="channelLoading"
      :params="channelsUserName"
      is-update
      is-channels
      @upload="handleFetchWechatChannelList"
    />
    <!--单视频-->
    <template v-if="elementsKey.short_video_struct">
      <n-grid x-gap="12" :cols="1" class="template-element_story">
        <n-gi
          v-for="(item, index) in elements[elementsKey.short_video_struct.index].children"
          :key="index"
          class="ad-template-group"
        >
          <!--此处为循环对象-->
          <TemplateMedia
            :ref="(el) => setItemRef(el, item.name + index)"
            :params="item"
            :material="mediaPreset"
            is-material
            @change="videoChange"
          />
        </n-gi>
      </n-grid>
    </template>
    <!--单图片-->
    <template v-if="elementsKey.video || elementsKey.image">
      <n-grid x-gap="12" :cols="1" class="template-element_story">
        <n-gi v-if="elementsKey.image_list" class="ad-template-group">
          <TemplateMedia
            :ref="(el) => setItemRef(el, elementsKey.image_list.name)"
            :params="elements[elementsKey.image_list.index].children[0]"
            :material="mediaPreset"
            is-material
          />
        </n-gi>
      </n-grid>
    </template>
    <!--单图片、单视频-->
    <template v-if="elementsKey.video || elementsKey.image">
      <n-grid x-gap="12" :cols="1" class="template-element_story">
        <n-gi v-if="elementsKey.video" class="ad-template-group">
          <TemplateMedia
            :ref="(el) => setItemRef(el, elementsKey.video.name)"
            :key="elementsKey.video.name"
            :params="elements[elementsKey.video.index]"
            :material="mediaPreset"
            is-material
            @change="videoChange"
          />
        </n-gi>
        <n-gi v-if="elementsKey.image" class="ad-template-group">
          <TemplateMedia
            :ref="(el) => setItemRef(el, elementsKey.image.name)"
            :key="elementsKey.image.name"
            :params="elements[elementsKey.image.index]"
          />
        </n-gi>
      </n-grid>
    </template>
    <!--多个媒体素材-->
    <template v-if="fileList">
      <n-grid x-gap="12" :cols="1" class="template-element_story">
        <n-gi v-for="(item, index) in elements[fileList.index].children" :key="index" class="ad-template-group">
          <!--图片-->
          <TemplateMedia
            v-if="Object.keys(item).length === 1"
            :ref="(el) => setItemRef(el, item.name + index)"
            :params="item[Object.keys(item)[0]]"
            :material="mediaPreset"
            :material-index="index"
            is-material
          />
          <TemplateMedia
            v-else
            :ref="(el) => setItemRef(el, item.name + index)"
            :params="item"
            :material="mediaPreset"
            :material-index="index"
            is-material
          />
        </n-gi>
      </n-grid>
    </template>
    <!--多文案-->
    <template v-if="elementsKey.title_options">
      <template v-for="(item, index) in elements[elementsKey.title_options.index].children" :key="item.name + index">
        <TemplateText
          :ref="(el) => setItemRef(el, item.name)"
          :params="item"
          :dynamic="false"
          :textarea="isTextarea"
          expression
        />
      </template>
    </template>
    <!--多文案-->
    <template v-if="elementsKey.description_options">
      <template
        v-for="(item, index) in elements[elementsKey.description_options.index].children"
        :key="item.name + index"
      >
        <TemplateText
          :ref="(el) => setItemRef(el, item.name)"
          :params="item"
          :dynamic="false"
          :textarea="isTextarea"
          expression
        />
      </template>
    </template>
    <!--  广告文案  -->
    <TemplateText
      v-if="elementsKey.title"
      :ref="(el) => setItemRef(el, elementsKey.title.name)"
      :key="elementsKey.title.name"
      :params="elements[elementsKey.title.index]"
      :dynamic="false"
      :textarea="isTextarea"
      expression
    />
    <!--  广告描述  -->
    <TemplateText
      v-if="elementsKey.description"
      :ref="(el) => setItemRef(el, elementsKey.description.name)"
      :key="elementsKey.description.name"
      :params="elements[elementsKey.description.index]"
      :textarea="isTextarea"
      :is-length-controller="isLengthController"
      :dynamic="false"
      expression
    />
    <!--投放页面类型-->
    <TemplatePage
      v-if="landing_page_config"
      :ref="(el) => setItemRef(el, landing_page_config.support_page_type_list[0].page_type)"
      :key="landing_page_config"
      :params="landing_page_config"
      @changeMaterial="onChangeMaterial"
      @change="onChangeCanvas"
      @changeLinkNameType="onChangeLinkNameType"
      @actionChange="onActionChange"
    />
    <!--按钮文案-->
    <TemplateText
      v-if="elementsKey.button_text"
      :ref="(el) => setItemRef(el, elementsKey.button_text.name)"
      :key="elementsKey.button_text.name"
      :params="elements[elementsKey.button_text.index]"
      @change="onChangeLinkNameType"
    />
    <!--跳转落地页-->
    <template v-if="landing_page_type === 'PAGE_TYPE_CANVAS_WECHAT'">
      <TemplateRadio
        v-if="attributesKey.link_page_type"
        :ref="(el) => setItemRef(el, attributesKey.link_page_type.name)"
        :key="attributesKey.link_page_type.name"
        :params="attributes[attributesKey.link_page_type.index]"
        :retain="link_page_type_retain"
        :filter="link_page_type_filter"
        @change="onChangePageType"
      />
    </template>
    <!--数据展示转化行为-->
    <TemplateRadio
      v-if="attributesKey.conversion_data_type"
      :ref="(el) => setItemRef(el, attributesKey.conversion_data_type.name)"
      :key="attributesKey.conversion_data_type.name"
      :params="attributes[attributesKey.conversion_data_type.index]"
      @switch="onSwitchConversionButton"
    />
    <div v-if="isConversionTargetType">
      <TemplateRadio
        v-if="attributesKey.conversion_target_type"
        :ref="(el) => setItemRef(el, attributesKey.conversion_target_type.name)"
        :key="attributesKey.conversion_target_type.name"
        :params="attributes[attributesKey.conversion_target_type.index]"
        :retain="conversion_target_list"
      />
    </div>
    <!--标签-->
    <TemplateLabel
      v-if="elementsKey.label"
      :ref="(el) => setItemRef(el, elementsKey.label.name)"
      :key="elementsKey.label.name"
      :params="elements[elementsKey.label.index]"
    />
    <!--头像及昵称跳转页-->
    <TemplateAvatar
      v-if="attributesKey.profile_id"
      :ref="(el) => setItemRef(el, attributesKey.profile_id.name)"
      :key="attributesKey.profile_id.name"
      :params="attributes[attributesKey.profile_id.index]"
    />
    <!--品牌标识-->
    <TemplateBrand
      v-else-if="Brand"
      :ref="(el) => setItemRef(el, Brand.name)"
      :key="Brand.name"
      :params="elements[Brand.index]"
    />
    <!--左下辅助文案-->
    <TemplateText
      v-if="elementsKey.bottom_text"
      :ref="(el) => setItemRef(el, elementsKey.bottom_text.name)"
      :key="elementsKey.bottom_text.name"
      :params="elements[elementsKey.bottom_text.index]"
    />
    <!--次行文案-->
    <TemplateText
      v-if="elementsKey.caption"
      :ref="(el) => setItemRef(el, elementsKey.caption.name)"
      :key="elementsKey.caption.name"
      :params="elements[elementsKey.caption.index]"
    />
    <!--第三行文案-->
    <TemplateText
      v-if="elementsKey.left_bottom_txt"
      :ref="(el) => setItemRef(el, elementsKey.left_bottom_txt.name)"
      :key="elementsKey.left_bottom_txt.name"
      :params="elements[elementsKey.left_bottom_txt.index]"
    />
    <!--复选框-->
    <TemplateCheckbox
      v-if="attributesKey.multi_share_optimization_enabled"
      :ref="(el) => setItemRef(el, attributesKey.multi_share_optimization_enabled.name)"
      :key="attributesKey.multi_share_optimization_enabled.name"
      :params="attributes[attributesKey.multi_share_optimization_enabled.index]"
    />
    <!--视频号浮层卡片-->
    <!--TemplateMedia ref报警告-->
    <template v-if="floatingZoneStruct && siteSet.includes('SITE_SET_CHANNELS')">
      <!--      <TemplateMedia-->
      <!--        :ref="(el) => setItemRef(el, floatingZoneStruct.image_id)"-->
      <!--        :key="floatingZoneStruct.image_id.name"-->
      <!--        :params="floatingZoneStruct.image_id"-->
      <!--      />-->
      <!--确保唯一值 加了uuid-->
      <TemplateMedia
        :ref="(el) => setItemRef(el, floatingZoneStruct.image_id + uuid)"
        :key="floatingZoneStruct.image_id.name"
        :params="floatingZoneStruct.image_id"
      />
      <TemplateText
        v-if="floatingZoneStruct.name"
        :ref="(el) => setItemRef(el, floatingZoneStruct.name.name)"
        :key="floatingZoneStruct.name.name"
        :params="floatingZoneStruct.name"
      />
      <TemplateText
        v-if="floatingZoneStruct.desc"
        :ref="(el) => setItemRef(el, floatingZoneStruct.desc.name)"
        :key="floatingZoneStruct.desc.name"
        :params="floatingZoneStruct.desc"
      />
      <TemplateText
        v-if="floatingZoneStruct.button_text"
        :ref="(el) => setItemRef(el, floatingZoneStruct.button_text.name)"
        :key="floatingZoneStruct.button_text.name"
        :params="floatingZoneStruct.button_text"
      />
    </template>
  </div>
</template>

<script setup lang="ts">
  import { useRoute } from 'vue-router'
  const route = useRoute()
  import { computed, onMounted, reactive, ref, watch } from 'vue'
  import { useStore } from '@/store'
  import { NGrid, NGi } from 'naive-ui'
  import TemplateText from '@/views/advertising/ads/create/components/step7/TemplateText.vue'
  import TemplateMedia from '@/views/advertising/ads/create/components/step7/TemplateMedia.vue'
  import TemplateCheckbox from '@/views/advertising/ads/create/components/step7/TemplateCheckbox.vue'
  import TemplateBrand from '@/views/advertising/ads/create/components/step7/TemplateBrand.vue'
  import TemplateLabel from '@/views/advertising/ads/create/components/step7/TemplateLabel.vue'
  import TemplateRadio from '@/views/advertising/ads/create/components/step7/TemplateRadio.vue'
  import TemplateAvatar from '@/views/advertising/ads/create/components/step7/TemplateAvatar.vue'
  import TemplatePage from '@/views/advertising/ads/create/components/step7/TemplatePage.vue'

  const store = useStore()
  const props = defineProps({
    detail: {
      type: Object,
      default: () => ({})
    }
  })
  const getProps = reactive(props)
  const isEdit = computed(() => {
    return !!store.state.intelligent.data.id
  })
  const creative = computed(() => {
    return store.state.intelligent.data.creative
  })
  const position = computed(() => {
    return store.state.intelligent.data.position
  })
  const base = computed(() => {
    return store.state.intelligent.data.base
  })
  const siteSet = computed(() => {
    return store.state.intelligent.data.position.siteSet
  })
  const attributes = computed(() => {
    return getProps.detail ? getProps.detail.adcreative_attributes : []
  })
  const accountCode = computed(() => {
    return store.state.intelligent.data.accountCode
  })
  const attributesKey = computed(() => {
    const keys = {}
    attributes.value.forEach((item, index) => {
      keys[item.name] = {
        index,
        name: item.name
      }
    })
    return keys
  })
  const elements = computed(() => {
    return getProps.detail ? getProps.detail.adcreative_elements : []
  })
  const elementsKey = computed(() => {
    const keys = {}
    elements.value.forEach((item, index) => {
      keys[item.name] = {
        index,
        name: item.name
      }
    })
    // console.log(keys)
    return keys
  })
  const isCard = computed(() => {
    return [450, 452, 588, 589].some((item) => item === creative.value.templateId)
  })
  const isTextarea = computed(() => {
    return [263, 310, 311, 618, 641, 642, 643, 644, 645, 646, 647, 648, 649, 721, 1064, 1465, 1480].some(
      (item) => item === creative.value.templateId
    )
    // return [599, 720, 721, 722, 910, 1529].some((item) => item === creative.value.templateId)
  })
  const fileList = computed(() => {
    const list =
      elementsKey.value.image_list || elementsKey.value.short_video_struct_options || elementsKey.value.video_options
    if (list && elements.value[list.index].children.length > 1) {
      return list
    } else {
      return false
    }
  })
  const canvasPageList = computed(() => {
    if (attributesKey.value.canvas_page) {
      const params = attributes.value[attributesKey.value.canvas_page.index]
      const enumeration = params.enum_property.enumeration || []
      params.enum_property.enumeration = enumeration.map((item) => {
        let page_elements_spec_list = item.page_elements_spec_list || []
        if (page_elements_spec_list && typeof page_elements_spec_list === 'string') {
          page_elements_spec_list = JSON.parse(page_elements_spec_list)
        }
        return {
          ...item,
          page_elements_spec_list
        }
      })
      return params
    } else {
      return []
    }
  })
  const isConversionTargetType = computed(() => {
    return (
      attributesKey.value.conversion_data_type &&
      attributes.value[attributesKey.value.conversion_data_type.index].default
    )
  })
  const channelsUserName = computed(() => {
    if (elementsKey.value.wechat_channels_spec) {
      return elements.value[elementsKey.value.wechat_channels_spec.index].children.username
    } else {
      return null
    }
  })
  const isLengthController = computed(() => {
    return landing_page_config.value.moment_action_button?.default && [1707, 1708].includes(creative.value.templateId)
  })
  // 品牌标识
  const Brand = computed(() => {
    return elementsKey.value.brand || elementsKey.value.corporate
  })
  const landing_page_config = computed(() => {
    return getProps.detail.landing_page_config
  })
  const floatingZoneStruct = computed(() => {
    return elementsKey.value.floating_zone_struct
      ? elements.value[elementsKey.value.floating_zone_struct.index].children
      : null
  })
  const landing_page_type = ref()
  const link_page_type = ref()
  const current_canvas_page = ref(false)
  const override_canvas_head_option = ref('OPTION_CREATIVE_OVERRIDE_CANVAS')
  const mediaPreset = ref(null)
  const link_page_type_retain = ref('')
  const link_page_type_filter = ref('')
  const conversion_target_list = ref('')
  const self_support_page_default_value = ref('')
  const self_support_page_filter = ref('')
  const upload_loading = ref(false)
  const overrideOption = ref('')
  const channelLoading = ref(false)
  const channelsId = ref('')
  const grabValue = ref('')
  const itemRefs = {}
  const setItemRef = (el: any, key) => {
    if (el) {
      itemRefs[key] = el
    }
  }

  onMounted(() => {
    // 回填数据
    if (canvasPageList.value.default) {
      // 当前原生推广页
      const enumeration = attributes.value[attributesKey.value.canvas_page.index].enum_property.enumeration
      current_canvas_page.value = enumeration.find((item) => item.value === canvasPageList.value.default)
    }
    try {
      if (!isEdit.value && creative.value.templateId === 1480) {
        // 微信朋友圈竖版视频9：16，默认选择原生推广页
        const find = attributes.value[attributesKey.value.self_support_page.index]
        // 为空的时候，设置默认值
        if (!find.default) {
          landing_page_type.value = 'PAGE_TYPE_CANVAS_WECHAT'
          find.default = 'PAGE_TYPE_CANVAS_WECHAT'
        }
      }
    } catch (e) {
      console.warn(e)
    }
  })
  async function validate() {
    // 如果没有数据展示转换行为 删除指向的ref
    if (!isConversionTargetType.value) {
      try {
        delete itemRefs[attributesKey.value.conversion_target_type.name]
      } catch (e) {}
    }
    return new Promise(async (resolve, reject) => {
      const refs = itemRefs || []
      let is = true
      for (const key in refs) {
        let ref = refs[key]
        if (Object.prototype.toString.call(refs[key]) === '[object Array]') {
          ref = ref[0]
        }
        try {
          // 校验不通过，跳出循环
          if (ref && !(await ref.validate())) {
            is = false
            break
          }
        } catch (e) {
          is = true
        }
      }
      resolve(is)
    })
  }
  // 数据展示转化行为按钮切换
  function onSwitchConversionButton(val) {
    if (!val) {
      // 根据开关控制清空行动按钮文案
      try {
        attributes.value[attributesKey.value.conversion_target_type.index].default = null
      } catch (e) {
        console.log('onSwitchConversionButton->', e)
      }
    }
  }
  // 素材替换，切换是否使用外层素材
  function onChangeMaterial(list: any, val: any) {
    override_canvas_head_option.value = val
    if (list.length > 1) {
      if (override_canvas_head_option.value?.includes('OPTION_CANVAS_OVERRIDE_CREATIVE')) {
        mediaPreset.value = current_canvas_page.value ? current_canvas_page.value.page_elements_spec_list : null
      } else {
        mediaPreset.value = null
      }
    } else {
      if (override_canvas_head_option.value?.includes('OPTION_CREATIVE_OVERRIDE_CANVAS')) {
        mediaPreset.value = null
      } else {
        mediaPreset.value = current_canvas_page.value ? current_canvas_page.value.page_elements_spec_list : null
      }
    }
    getProps.detail.landing_page_config.material_replace = val?.length > 0 ? val : ''
  }
  // 原生推广页切换
  function onChangeCanvas(list: any, val: any) {
    console.log(val, 'onChangeCanvas', list)
    const find = val
    // // 当前原生推广页
    // current_canvas_page.value = find
    if (list.length > 1) {
      // 当有多个选项时，只有勾选了使用原生推广页顶部素材作为外层素材才换视频
      if (override_canvas_head_option.value?.includes('OPTION_CANVAS_OVERRIDE_CREATIVE')) {
        try {
          if (val) {
            mediaPreset.value = find.page_elements_spec_list
          } else {
            mediaPreset.value = null
          }
        } catch (e) {
          console.warn('原生推广页切换，替换素材失败', e)
        }
      }
    } else {
      // 不勾选使用外层创意素材替换原生推广页
      if (!override_canvas_head_option.value?.includes('OPTION_CREATIVE_OVERRIDE_CANVAS')) {
        try {
          if (val) {
            mediaPreset.value = find.page_elements_spec_list
          } else {
            mediaPreset.value = null
          }
        } catch (e) {
          console.warn('原生推广页切换，替换素材失败', e)
        }
      }
    }
  }
  // 按钮文案切换，联动转化行为
  function onChangeLinkNameType(val, options) {
    // console.log(val, options, 4444444)
    // conversion_target_type
    try {
      const find = attributes.value[attributesKey.value.conversion_target_type.index]
      conversion_target_list.value = options.conversion_target_list || []
      if (['WATCH_LIVE'].includes(val)) {
        // 观看直播的不支持 数据展示数据类型
        attributes.value[attributesKey.value.conversion_data_type.index].default = false
        conversion_target_list.value = []
        find.default = null
      } else {
        if (!isEdit.value) {
          if (isConversionTargetType.value && conversion_target_list.value.length) {
            find.default = conversion_target_list.value[0].value
          } else {
            find.default = null
          }
        }
      }
      // console.log(isShow);
    } catch (e) {
      console.warn('selfAttributesKey.conversion_target_type 不存在')
      // 初始化默认数据
      if (attributesKey.value.conversion_target_type) {
        conversion_target_list.value =
          attributes.value[attributesKey.value.conversion_target_type.index].property_detail.enum_detail.enumeration
      }
    }
  }
  // 行动按钮切换
  function onActionChange(val, list) {
    if (!val) {
      conversion_target_list.value = list[0].conversion_target_list || []
    }
  }
  // 选择行动按钮
  function onChangePageType(val) {
    // 微信小程序
    // console.log(val);
    // LINK_PAGE_TYPE_MINI_PROGRAM_WECHAT
    link_page_type.value = val
  }
  function handleFetchWechatChannelList() {
    channelLoading.value = true
    store
      .dispatch('intelligent/getAdsWechatChannel', {
        accountCode: accountCode.value
      })
      .then((res) => {
        channelLoading.value = false
        const params = elementsKey.value.username
          ? attributes.value[elementsKey.value.username.index]
          : channelsUserName.value
        params.enum_property.enumeration = res.data
      })
      .catch(() => {
        channelLoading.value = false
      })
  }
  function handleWeChatChannelsChange(value, item) {
    channelsId.value = value
    grabValue.value = item ? item.grabValue : ''
  }
  // 视频上传自动使用首帧作为封面图
  function videoChange(val) {
    if (elementsKey.value.image) {
      const params = elements.value[elementsKey.value.image.index]
      store
        .dispatch('intelligent/mediaUpload', {
          accountCode: accountCode.value,
          keyFrameImageUrl: val.keyFrameImageUrl,
          fileType: '1'
        })
        .then((res: any) => {
          params.default = res.data.mediaId
          params.file = res.data.previewUrl
          params.fileUrl = res.data.previewUrl
        })
    }
  }
  defineExpose({
    validate
  })
</script>

<style scoped lang="scss"></style>
